package com.fpx.order.plat.web.utils;



import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextHolder implements ApplicationContextAware,
		DisposableBean {
	
	private static Log logger = LogFactory.getLog(SpringContextHolder.class);
	
	/**
	 * Spring应用上下文环境  
	 */
	private static ApplicationContext applicationContext = null;
	
	/**
	 * 获得容器上下文对象
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		assertContextInjected();
		return applicationContext;
	}
	
	/**
	 * IOC设置容器上下文
	 */
	public void setApplicationContext(ApplicationContext applicationContext)throws BeansException{
		logger.info("注入ApplicationContext到SpringContextHolder:"
				+ applicationContext);
		if (SpringContextHolder.applicationContext != null) {
			logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:"
					+ SpringContextHolder.applicationContext);
		}
		SpringContextHolder.applicationContext = applicationContext; // NOSONAR
	}
	
	@Override
	public void destroy() throws Exception {
		SpringContextHolder.clear();
	}

	
	/**
	 * 获取实体类的实例化对象
	 * @param name
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		assertContextInjected();
		return (T) applicationContext.getBean(name);
	}
	/**
	 * 获取实体类的实例化对象
	 * @param name
	 * @param class
	 * @return
	 */
	public static <T> T getBean(String name, Class<T> requiredType) {
		assertContextInjected();
		return applicationContext.getBean(name, requiredType);
	}

	public static void clear() {
		logger.warn("清除SpringContextHolder中的ApplicationContext:"
				+ applicationContext);
		applicationContext = null;
	}

	private static void assertContextInjected() {
		if (applicationContext == null) {
			throw new IllegalStateException(
					"applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
		}
	}
}
